package com.iakuil.app.common.restful;

import com.iakuil.app.common.core.constant.SysConstant;
import com.iakuil.app.common.core.util.StringUtils;
import com.iakuil.app.common.restful.filter.RequestIdFilter;
import com.iakuil.app.common.restful.filter.XssFilter;
import jakarta.servlet.DispatcherType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;

import java.util.HashMap;
import java.util.Map;

/**
 * WebApp Filter自动配置
 *
 * @author Kai
 */
@AutoConfiguration
@ConditionalOnClass(WebMvcAutoConfiguration.class)
public class WebFilterAutoConfiguration {

    @Value("${app.xss.excludes:/xxx}")
    private String xssExcludes;

    @Value("${app.xss.urlPatterns:/*}")
    private String urlPatterns;

    @Bean
    @ConditionalOnProperty(value = SysConstant.APP_SYMBOL + ".xss.enabled", havingValue = "true")
    public FilterRegistrationBean<XssFilter> xssFilterRegistration() {
        FilterRegistrationBean<XssFilter> registration = new FilterRegistrationBean<>();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new XssFilter());
        registration.addUrlPatterns(StringUtils.split(urlPatterns, ","));
        registration.setName("xssFilter");
        registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
        Map<String, String> initParameters = new HashMap<>();
        initParameters.put("excludes", xssExcludes);
        registration.setInitParameters(initParameters);
        return registration;
    }

    /**
     * Request id过滤器
     */
    @Bean
    public FilterRegistrationBean<RequestIdFilter> requestIdFilter() {
        FilterRegistrationBean<RequestIdFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new RequestIdFilter());
        registrationBean.setName("requestIdFilter");
        registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
        registrationBean.addUrlPatterns("/api/*");
        return registrationBean;
    }
}
